<!-- src/views/operations/ProcessingDialog.vue -->
<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="90%"
    style="max-height: 700px;"
    @close="onClose"
  >
    <div class="processing-dialog-container">
      <!-- 上方来源列表 -->
      <div class="top-panel">
        <div class="panel-header">
          <h3>来源</h3>
          <el-button 
            v-if="!readonly"
            size="small" 
            type="primary" 
            plain 
            @click="handleAddSource"
            style="float: right; margin-top: -20px;"
          >
            <el-icon><Plus /></el-icon> 添加
          </el-button>
        </div>
        
        <div class="table-wrapper">
          <el-table
            :data="leftTableData"
            border
            style="width: 100%;"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" v-if="!readonly" />
            <el-table-column prop="code" label="商品编码" min-width="120" />
            <el-table-column prop="name" label="商品名称" min-width="120" />
            <el-table-column prop="warehouseAreaLocaName" label="库位" min-width="120" />
            <el-table-column prop="count" :label="readonly ? '数量' : '可编辑数量'" width="120">
              <template #default="scope">
                <span v-if="readonly">{{ scope.row.count }}</span>
                <el-input-number 
                  v-else
                  v-model="scope.row.count" 
                  :min="1" 
                  :max="scope.row.originalCount"
                  size="small"
                  style="width: 100%"
                  @change="handleCountChange(scope.row, $event)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" fixed="right" v-if="!readonly">
              <template #default="scope">
                <el-button 
                  size="small" 
                  type="danger" 
                  link 
                  @click="handleRemoveFromSource(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 下方目标列表 -->
      <div class="bottom-panel">
        <div class="panel-header">
          <h3>目标</h3>
          <el-button 
            v-if="!readonly"
            size="small" 
            type="primary" 
            plain 
            @click="handleAddTarget"
            style="float: right; margin-top: -20px;"
          >
            <el-icon><Plus /></el-icon> 添加
          </el-button>
        </div>
        
        <div class="table-wrapper">
          <el-table
            :data="rightTableData"
            border
            style="width: 100%;"
            @selection-change="handleTargetSelectionChange"
          >
            <el-table-column type="selection" width="55" v-if="!readonly" />
            <el-table-column prop="code" label="商品编码" min-width="120" />
            <el-table-column prop="title" label="商品名称" min-width="120" />
            <el-table-column prop="targetCount" :label="readonly ? '数量' : '可编辑数量'" width="120">
              <template #default="scope">
                <span v-if="readonly">{{ scope.row.targetCount }}</span>
                <el-input-number
                  v-else
                  v-model="scope.row.targetCount"
                  :min="1"
                  size="small"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column prop="targetLocation" label="目标库位" min-width="120" />
            <el-table-column label="操作" width="150" fixed="right" v-if="!readonly">
              <template #default="scope">
                <el-button 
                  size="small" 
                  type="primary" 
                  link 
                  @click="handleSelectLocation(scope.row)"
                >
                  选择库位
                </el-button>
                <el-button 
                  size="small" 
                  type="danger" 
                  link 
                  @click="handleRemoveFromTarget(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" fixed="right" v-if="readonly">
              <template #default="scope">
                <el-button 
                  size="small" 
                  type="primary" 
                  link 
                  @click="handleViewLocation(scope.row)"
                >
                  查看库位
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <template #footer v-if="!readonly">
      <span class="dialog-footer">
        <el-button @click="close">关闭</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </span>
    </template>
    <template #footer v-else>
      <span class="dialog-footer">
        <el-button @click="close">关闭</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 商品选择弹框（来源） -->
  <ProductSelectionDialog 
    v-if="!readonly"
    ref="productSelectionDialogRef" 
    @confirm="handleProductSelectionConfirm"
  />
  
  <!-- 目标商品选择弹框 -->
  <TargetProductSelection
    v-if="!readonly"
    ref="targetProductSelectionRef"
    @confirm="handleTargetProductSelectionConfirm"
  />
  
  <!-- 库位查看弹窗 -->
  <el-dialog
    v-model="locationViewDialogVisible"
    title="库位信息"
    width="500px"
  >
    <el-form :model="locationViewForm" label-width="100px">
      <el-form-item label="仓库">
        <el-input v-model="locationViewForm.warehouseName" disabled />
      </el-form-item>
      <el-form-item label="库区">
        <el-input v-model="locationViewForm.areaName" disabled />
      </el-form-item>
      <el-form-item label="库位">
        <el-input v-model="locationViewForm.locationName" disabled />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="locationViewDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
  
  <!-- 库位选择弹窗 -->
  <el-dialog
    v-if="!readonly"
    v-model="locationDialogVisible"
    title="选择库位"
    width="500px"
  >
    <el-form :model="locationForm" label-width="100px">
      <el-form-item label="仓库">
        <el-select 
          v-model="locationForm.warehouseId" 
          placeholder="请选择仓库"
          clearable
          style="width: 100%"
          @change="handleWarehouseChange"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库区">
        <el-select 
          v-model="locationForm.warehouseAreaId" 
          placeholder="请选择库区"
          clearable
          style="width: 100%"
          @change="handleAreaChange"
        >
          <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库位">
        <el-select 
          v-model="locationForm.warehouseAreaLocaId" 
          placeholder="请选择库位"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in locaList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="locationDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmLocationSelection">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import ProductSelectionDialog from './ProductSelectionDialog.vue'
import TargetProductSelection from './TargetProductSelection.vue'
import { getWarehouseListApi } from '@/api/warehouse'
import { getWarehouseAreaListApi } from '@/api/warehouseArea'
import { getWarehouseLocaListApi } from '@/api/warehouseAreaLoca'
import { addOperationsApi} from '@/api/operations/operations.js'

//获取当前Vue实例
const instance = getCurrentInstance()

// 弹窗状态
const visible = ref(false)

// 弹窗标题
const title = ref('')

// 左侧来源列表数据
const leftTableData = ref([])

// 右侧目标列表数据
const rightTableData = ref([])

// 选中的行数据
const selectedRows = ref([])

// 目标列表选中数据
const targetSelectedRows = ref([])

// 商品选择弹框引用
const productSelectionDialogRef = ref(null)
const targetProductSelectionRef = ref(null)

// 当前操作类型（split-拆分，combine-组合）
const currentOperationType = ref('')

// 是否只读模式
const readonly = ref(false)

// 库位选择弹窗相关
const locationDialogVisible = ref(false)
const currentTargetRow = ref(null)
const locationForm = ref({
  warehouseId: '',
  warehouseAreaId: '',
  warehouseAreaLocaId: ''
})

// 库位查看弹窗相关
const locationViewDialogVisible = ref(false)
const locationViewForm = ref({
  warehouseName: '',
  areaName: '',
  locationName: ''
})

// 仓库、库区、库位数据
const warehouseList = ref([])
const areaList = ref([])
const locaList = ref([])

// 打开弹窗
const open = (options) => {
  // 设置弹窗标题
  title.value = options.title || '加工处理'
  
  // 设置只读模式
  readonly.value = options.readonly || false
  
  // 初始化数据
  leftTableData.value = options.sourceData || []
  rightTableData.value = options.targetData || []
  
  // 记录操作类型
  currentOperationType.value = options.title === '拆分加工' || options.title === '拆分加工详情' ? 'split' : 'combine'
  
  // 显示弹窗
  visible.value = true
  
  // 如果不是只读模式，获取仓库列表
  if (!readonly.value) {
    getWarehouseList()
  }
}

// 关闭弹窗
const close = () => {
  visible.value = false
  selectedRows.value = []
  targetSelectedRows.value = []
  currentOperationType.value = ''
  readonly.value = false
}

// 关闭时重置数据
const onClose = () => {
  selectedRows.value = []
  targetSelectedRows.value = []
  currentOperationType.value = ''
  readonly.value = false
}

// 处理来源列表选择
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 处理目标列表选择
const handleTargetSelectionChange = (val) => {
  targetSelectedRows.value = val
}

// 从来源列表删除
const handleRemoveFromSource = (row) => {
  leftTableData.value = leftTableData.value.filter(item => item.id !== row.id)
}

// 从目标列表删除
const handleRemoveFromTarget = (row) => {
  rightTableData.value = rightTableData.value.filter(item => item.id !== row.id)
}

// 添加来源商品
const handleAddSource = () => {
  // 根据操作类型决定选择模式
  const selectionMode = currentOperationType.value === 'split' ? 'single' : 'multiple'
  
  productSelectionDialogRef.value.open({
    title: '选择来源商品',
    selectionMode: selectionMode
  })
}

// 添加目标商品
const handleAddTarget = () => {
  // 根据操作类型决定选择模式（与来源相反）
  const selectionMode = currentOperationType.value === 'split' ? 'multiple' : 'single'
  
  targetProductSelectionRef.value.open({
    title: '选择目标商品',
    selectionMode: selectionMode
  })
}

// 处理商品选择确认（来源）
const handleProductSelectionConfirm = (selectedProducts) => {
  // 将选中的商品添加到左侧来源列表
  selectedProducts.forEach(product => {
    // 检查是否已存在
    const exists = leftTableData.value.some(item => item.id === product.id)
    if (!exists) {
      leftTableData.value.push({
        ...product,
        name: product.title, // 使用title作为name
        originalCount: product.count // 保存原始数量用于校验
      })
    }
  })
}

// 处理目标商品选择确认
const handleTargetProductSelectionConfirm = (selectedProducts) => {
  // 将选中的商品添加到右侧目标列表
  selectedProducts.forEach(product => {
    // 检查是否已存在
    const exists = rightTableData.value.some(item => item.id === product.id)
    if (!exists) {
      rightTableData.value.push({
        ...product,
        targetCount: product.targetCount,
        targetLocation: product.targetLocation
      })
    }
  })
}

// 处理数量修改
const handleCountChange = (row, value) => {
  if (value <= 0) {
    ElMessage.warning('数量必须大于0')
    // 恢复为原始值
    row.count = row.originalCount
    return
  }
  
  if (value > row.originalCount) {
    ElMessage.warning(`数量不能大于原始数量 ${row.originalCount}`)
    // 恢复为原始值
    row.count = row.originalCount
    return
  }
}

// 处理查看库位
const handleViewLocation = (row) => {
  // 这里可以调用后端接口获取详细的库位信息
  // 目前只是简单显示已有的信息
  locationViewForm.value = {
    warehouseName: '仓库名称', // 需要从后端获取
    areaName: '库区名称', // 需要从后端获取
    locationName: row.targetLocation
  }
  locationViewDialogVisible.value = true
}

// 处理选择库位
const handleSelectLocation = (row) => {
  currentTargetRow.value = row
  // 如果该行已有库位信息，则初始化表单
  if (row.targetLocationObj) {
    locationForm.value = { ...row.targetLocationObj }
  } else {
    locationForm.value = {
      warehouseId: '',
      warehouseAreaId: '',
      warehouseAreaLocaId: ''
    }
  }
  locationDialogVisible.value = true
  
  // 获取相关数据
  if (locationForm.value.warehouseId) {
    getAreaList(locationForm.value.warehouseId)
  }
  if (locationForm.value.warehouseAreaId) {
    getLocaList(locationForm.value.warehouseAreaId)
  }
}

// 确认库位选择
const confirmLocationSelection = () => {
  if (!locationForm.value.warehouseAreaLocaId) {
    ElMessage.warning('请选择库位')
    return
  }
  
  // 查找选中的库位名称
  const selectedLoca = locaList.value.find(item => item.id === locationForm.value.warehouseAreaLocaId)
  if (selectedLoca) {
    // 更新目标行的库位信息
    currentTargetRow.value.targetLocation = selectedLoca.name
    currentTargetRow.value.targetLocationObj = { ...locationForm.value }
    // 保存库位ID，用于提交时使用
    currentTargetRow.value.targetWarehouseAreaLocaId = locationForm.value.warehouseAreaLocaId
  }
  
  locationDialogVisible.value = false
}

// 获取仓库列表
const getWarehouseList = async () => {
  try {
    const res = await getWarehouseListApi()
    if (res.code === 1) {
      warehouseList.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取仓库列表失败')
  }
}

// 获取库区列表
const getAreaList = async (warehouseId) => {
  if (!warehouseId) {
    areaList.value = []
    return
  }
  
  try {
    const res = await getWarehouseAreaListApi(warehouseId)
    if (res.code === 1) {
      areaList.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取库区列表失败')
  }
}

// 获取库位列表
const getLocaList = async (areaId) => {
  if (!areaId) {
    locaList.value = []
    return
  }
  
  try {
    const res = await getWarehouseLocaListApi(areaId)
    if (res.code === 1) {
      locaList.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取库位列表失败')
  }
}

// 处理仓库选择变化
const handleWarehouseChange = (warehouseId) => {
  locationForm.value.warehouseAreaId = ''
  locationForm.value.warehouseAreaLocaId = ''
  areaList.value = []
  locaList.value = []
  getAreaList(warehouseId)
}

// 处理库区选择变化
const handleAreaChange = (areaId) => {
  locationForm.value.warehouseAreaLocaId = ''
  locaList.value = []
  getLocaList(areaId)
}

// 提交处理
const handleSubmit = async () => {
  if (leftTableData.value.length === 0 && rightTableData.value.length === 0) {
    ElMessage.warning('请至少添加一个商品')
    return
  }
  
  // 检查来源商品是否填写了数量
  const invalidSourceProducts = leftTableData.value.filter(item => !item.count || item.count <= 0)
  if (invalidSourceProducts.length > 0) {
    ElMessage.warning('请为所有来源商品填写有效数量')
    return
  }
  
  // 检查目标商品是否填写了数量和库位
  const invalidTargetProducts = rightTableData.value.filter(item => 
    !item.targetCount || item.targetCount <= 0 || !item.targetWarehouseAreaLocaId)
  if (invalidTargetProducts.length > 0) {
    ElMessage.warning('请为所有目标商品填写有效数量和选择库位')
    return
  }
  
  // 构造提交数据
  const submitData = {
    categoryOne: currentOperationType.value === 'split' ? 1 : 2, // 拆分加工为1，组合加工为2
    details: []
  }
  
  // 添加来源商品数据
  leftTableData.value.forEach(item => {
    submitData.details.push({
      skuId: item.skuId || item.id, // 使用skuId或id作为商品ID
      sourceCount: item.count,
      targetCount: null, // 来源商品targetCount为空
      targetWarehouseAreaLocaId: item.warehouseAreaLocaId, // 来源商品使用已有的库位ID
      category: 1 // 来源商品category为1
    })
  })
  
  // 添加目标商品数据
  rightTableData.value.forEach(item => {
    submitData.details.push({
      skuId: item.skuId || item.id, // 使用skuId或id作为商品ID
      sourceCount: null, // 目标商品sourceCount为空
      targetCount: item.targetCount,
      targetWarehouseAreaLocaId: item.targetWarehouseAreaLocaId, // 目标商品使用选择的库位ID
      category: 2 // 目标商品category为2
    })
  })
  
  try {
    // 调用后端接口提交数据
    const res = await addOperationsApi(submitData)
    if (res.code === 1) {
      ElMessage.success(`已提交${title.value}任务`)
      instance.emit('refresh')
      close()
    } else {
      ElMessage.error(res.msg || '提交失败')
    }
  } catch (error) {
    ElMessage.error('提交失败: ' + error.message)
  }
}

// 暴露方法
defineExpose({
  open,
  close
})
</script>

<style scoped>
.processing-dialog-container {
  display: flex;
  flex-direction: column;
  height: 500px;
  gap: 20px;
}

.top-panel, .bottom-panel {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  flex-shrink: 0;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.table-wrapper {
  flex: 1;
  overflow: auto;
  padding: 10px;
}

.table-wrapper :deep(.el-table) {
  height: 100%;
}

.table-wrapper :deep(.el-table__body-wrapper) {
  overflow-y: auto;
  overflow-x: auto;
}

.dialog-footer {
  text-align: right;
}
</style>